<?php

class GpsController extends Zend_Controller_Action
{

    public function init()
    {
        $this->_helper->layout->setLayout('layoutprofile');      
    }

    public function indexAction()
    {
        $obj = new Application_Model_Gps();
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        $imei = $obj->getAllImei($id_user);
        $this->view->imei = $imei;
    }

    public function navigationAction()
    {
        $obj = new Application_Model_Gps();
        $form = new Application_Form_Ajaximei();
        $this->view->form = $form;
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        $imei = $obj->getAllImei($id_user);
        $this->view->imei = $imei;
    }

    public function savegpsdataAction()
    {
        $obj = new Application_Model_Gps();
        //считываем весь файл        
        if (file_exists(APPLICATION_PATH.'/tracker/tracker.log')) {
            $file = file_get_contents(APPLICATION_PATH.'/tracker/tracker.log');        
            //и выбираем нужные параметры после "RMC"
            $big_arr = explode('GSr', $file);  
            //проходим циклом по всему массиву
            for ($i = 0; $i < count($big_arr); $i++) {
               //сплитим каждую запись, получая элементы массива
               $arr = explode(',', $big_arr[$i]);
               if (count($arr) == 8) {
                   //удаляем "+" вначале координат
                   $a = substr($arr[4], 1);
                   $b = substr($arr[3], 1);
                   //ставим точку после второй цифры координаты
                   $lat = substr($a, 0, 2).'.'.substr($a, 2, strlen($a));
                   $long = substr($b, 0, 2).'.'.substr($b, 2, strlen($a));               
                   //форматируем время и дату
                   $date = substr($arr[1], 4, 6).'.'.substr($arr[1], 2, -2).'.'.substr($arr[1], 0,2);
                   $time = substr($arr[2], 0, 2).'-'.substr($arr[2], 2, -2).'-'.substr($arr[2], 4,6);
                   $speed = $arr[5];
                   $battery = $arr[6];
                   //убираем лишнее с imei, imei[0] - нужное значение
                   $imei = explode('!', $arr[7]);
                   //получаем id imei, чтобы проверить есть ли такой в базе
                   $id_imei = $obj->getImeiId($imei[0]);
                   $id_route = $obj->getLastRoute($id_imei['id']);
                   echo $id_imei['id'];                   
                   //записываем координаты только зарегестрироанных устройств
                   if ($id_imei['id'] != null) {
                       //формируем массив для записи в бд
                       $data = array(
                                     //'imei'      => $imei[0],
                                     'id_imei'   => $id_imei['id'],
                                     'id_route'  => $id_route['id'],
                                     'latitude'  => $lat,
                                     'longitude' => $long,
                                     'speed'     => $speed,
                                     'battery'   => $battery,
                                     'date'      => $date.' '.$time
                       );                   
                       $obj->saveGpsData($data);               
                   }
               }                      
            } 

            file_put_contents(APPLICATION_PATH.'/tracker/tracker.log', '');
        }

    }

    public function addimeiAction()
    {
        $obj = new Application_Model_Gps();
        $form = new Application_Form_Imei();
        $this->view->form = $form;
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        
        if ($this->getRequest()->isPost()) {
            $postData = $this->getRequest()->getPost();
            if ($form->isValid($postData)) {               
                $data = array(
                    'id_user'     => $id_user,
                    'name'        => $form->getValue('name'),
                    'imei'        => $form->getValue('imei'),
                    'id_category' => $form->getValue('category')
                );
                                
                $id_imei = $obj->addImei($data);
                $data2 = array(
                    'id_imei' => $id_imei,
                    'id_user' => $id_user,
                    'name'    => $form->getValue('name').' '.date('d-m-Y')                    
                );
                $obj->newRoute($data2);
                $this->_helper->redirector('index', 'gps');
            }
        }
        
    }

    public function saverouteAction()
    {
        $obj = new Application_Model_Gps();        
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        if ($this->getRequest()->isPost()) {
            $imei = $this->getRequest()->getPost('imei');            
            $id_imei = $obj->getImeiId($imei);            
            $data = array(
                'id_imei'     => $id_imei['id'],
                'id_user'     => $id_user,
                'name'    => $id_imei['name'].' '.date('d-m-Y h:i')
            );
            $obj->newRoute($data);
        }   
    }

    public function showfullrouteAction()
    {
        $obj = new Application_Model_Gps();
        $id_imei = $this->_getParam('id');
        $routes = $obj->getAllRoutes($id_imei);
        $this->view->routes = $routes;
    }

    public function allimeiAction()
    {
        $obj = new Application_Model_Gps();
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        $imei = $obj->getAllImei($id_user);
        $this->view->imei = $imei;
    }

    public function inrealtimeAction()
    {
        // action body
    }

    public function saverealtimeAction()
    {
        $obj = new Application_Model_Gps();        
        $id_user = Zend_Auth::getInstance()->getIdentity()->id;
        if ($this->getRequest()->isPost()) {
            $id_imei = $this->getRequest()->getPost('id');            
            //$id_imei = $obj->getImeiId($imei);            
            //$name = $obj->getSelectImei($id_imei);
            $data = array(
                'id_imei'     => $id_imei,
                'id_user'     => $id_user,
                'name'    => $name[0]['name'].' '.date('d-m-Y h:i')
            );
            $obj->newRoute($data);
        }   
    }  
}

















